package org.jeecg.modules.zhoupackage.GoodsOrder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.gwcjava.jiekou.controller.BusinessLogiController;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.mapper.MyMlccThirdGoodsMapper;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.mapper.MyMlccThirdGoodsSeriesMapper;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.MlccThirdGoods;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.MlccThirdGoodsRange;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.MlccThirdGoodsSeries;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.MlccThirdGoodsandparameter;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.service.IGoodsCenterService;
import org.jeecg.modules.zhoupackage.GoodsOrder.mapper.MyMlccThirdCartBuynumMapper;
import org.jeecg.modules.zhoupackage.GoodsOrder.mapper.MyMlccThirdGoodsCartMapper;
import org.jeecg.modules.zhoupackage.GoodsOrder.mapper.MyMlccThirdGoodsOrderMapper;
import org.jeecg.modules.zhoupackage.GoodsOrder.pojo.MlccThirdCartBuynum;
import org.jeecg.modules.zhoupackage.GoodsOrder.pojo.MlccThirdGoodsCart;
import org.jeecg.modules.zhoupackage.GoodsOrder.pojo.MlccThirdGoodsOrder;
import org.jeecg.modules.zhoupackage.GoodsOrder.service.IGoodsOrderService;
import org.jeecg.modules.zhoupackage.GoodsOrder.util.GoodsOrderUtil;
import org.jeecg.modules.zhoupackage.mapper.MyMlccBusinessWaterInfoMapper;
import org.jeecg.modules.zhoupackage.mapper.MyTrackingOrderMapper;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class GoodsOrderServiceImpl implements IGoodsOrderService {

    @Autowired
    MyMlccThirdGoodsSeriesMapper goodsSeriesMapper;

    @Autowired
    MyMlccThirdGoodsMapper goodsMapper;

    @Autowired
    MyMlccThirdGoodsCartMapper cartMapper;

    @Autowired
    MyMlccThirdGoodsOrderMapper orderMapper;

    @Autowired
    MyMlccBusinessWaterInfoMapper businessWaterInfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyMlccThirdCartBuynumMapper cartBuynumMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    GoodsOrderUtil goodsOrderUtil;

    @Autowired
    IGoodsCenterService goodsCenterService;

    /**
     * 获取商品系列
     *
     * @param token 令牌
     */
    @Override
    public List<MlccThirdGoodsSeries> getGoodsSeries(String token) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        QueryWrapper<MlccThirdGoodsSeries> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        return goodsSeriesMapper.selectList(wrapper);
    }

    /**
     * 根据选中的商品类型获取名下的商品系列
     *
     * @param token 令牌
     * @param type  商品类型id
     */
    @Override
    public List<MlccThirdGoodsSeries> getGoodsSeriesByGoodsType(String token, String type) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        QueryWrapper<MlccThirdGoodsSeries> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        if (type != null && !"".equals(type)) {
            wrapper.eq("goods_type_id", type);
        }
        return goodsSeriesMapper.selectList(wrapper);
    }


    /**
     * 查询商品列表
     *
     * @param token      令牌
     * @param goodsGroup 商品系列
     * @param goodsCode  商品编号
     * @param goodsType  商品类型
     * @param page       分页器
     */
    @Override
    public IPage<MlccThirdGoods> getGoods(String token, String goodsGroup, String goodsCode, String goodsType, Page<MlccThirdGoods> page) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }

        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).eq("is_good", 0).eq("is_main", 0);
        if (goodsGroup != null && !"".equals(goodsGroup)) {
            wrapper.eq("goods_series_id", goodsGroup);
        }
        if (goodsType != null && !"".equals(goodsType)) {
            wrapper.eq("goods_type_id", goodsType);
        }
        if (goodsCode != null && !"".equals(goodsCode)) {
            wrapper.like("goods_code", goodsCode);
        }
        return goodsMapper.selectPage(page, wrapper);
    }

    /**
     * 根据token获取当前用户购物车列表
     *
     * @param token 令牌
     */
    @Override
    public List<MlccThirdGoodsCart> getCartList(String token) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccThirdGoodsCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userDetail.getId()).eq("status", 0);
        List<MlccThirdGoodsCart> carts = cartMapper.selectList(wrapper);
        // 统计购物车总价
        BigDecimal decimal = new BigDecimal(0);
        // 给购物车查询对应的现货信息
        if (carts != null && carts.size() > 0) {
            for (MlccThirdGoodsCart cart : carts) {
                MlccThirdGoods goods = goodsMapper.selectById(cart.getGoodsId());
                cart.setGoods(goods);
                decimal = decimal.add(cart.getSumMoney());
                // 查询阶梯价
                if (goods != null) {
                    if (goods.getIsMain() == 0) {
                        MlccThirdGoodsRange range = goodsOrderUtil.getGoodsRange(goods.getGoodsSeriesId(), cart.getGoodsNum());
                        cart.setRange(range);
                    }
                }
                // 查询购物车下每个产品不同规格的数量
                List<MlccThirdCartBuynum> byNum = goodsOrderUtil.getCartByNum(cart.getId());
                cart.setByNum(byNum);

                // 查询商品基本参数信息
                List<MlccThirdGoodsandparameter> goodsParam = goodsCenterService.goodsParam(cart.getGoodsId());
                cart.setGoodsParam(goodsParam);
            }
            for (MlccThirdGoodsCart cart : carts) {
                cart.setAllPrice(decimal.setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        }
        return carts;
    }

    /**
     * 删除购物车
     *
     * @param token 令牌
     * @param id    购物车id
     */
    @Override
    public int removeCart(String token, String id) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        int result = cartMapper.deleteById(id);
        if (result > 0) {
            // 删除大购物车名下的小购物车
            QueryWrapper<MlccThirdCartBuynum> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_cart_id", id);
            cartBuynumMapper.delete(wrapper);
        }
        return result;
    }

    /**
     * 创建未支付的面料订单
     *
     * @param token 令牌
     * @param order 订单类
     */
    @Override
    public String createFabricOrder(String token, MlccThirdGoodsOrder order) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 设置订单实体类基本信息
        // 创建一个随机数
        Random random = new Random();
        int i = random.nextInt(9999);
        order.setUserId(userDetail.getId() + "").setOrderSn("G" + System.currentTimeMillis() + i).setStatus(0).setSysOrgCode(userDetail.getOrgCode())
                .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
        /*获取订单总金额*/
        BigDecimal totalAmount = new BigDecimal(0);
        String[] cartids = order.getGoodsCartId().split(",");
        for (String cartid : cartids) {
            try {
                double lastDiscount = 1;
                // 获取购物车基本信息
                MlccThirdGoodsCart mlccCartInfo = cartMapper.selectById(cartid);
                // 获取商品ID
                String fabricId = mlccCartInfo.getGoodsId();
                MlccThirdGoods fabricInfo = goodsMapper.selectById(fabricId);
                // 获取购买数量
                String buyNumber = mlccCartInfo.getGoodsNum();

                // 计算订单总金额（每个购物车的金额相加）
                totalAmount = totalAmount.add(mlccCartInfo.getSumMoney());
            } catch (Exception e) {
                e.printStackTrace();
                return "-6";/*购物车已被清空，请勿重复支付*/
            }
        }
        //设置订单价格
        order.setOrderMoney(totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        int insert = orderMapper.insert(order);
        if (insert > 0) { // 添加成功之后需要改变购物车的状态
            System.out.println("订单编号是多少？" + order.getOrderSn());
            for (String cartid : cartids) {
                MlccThirdGoodsCart cartInfo = cartMapper.selectById(cartid);
                cartInfo.setStatus(2);
                cartMapper.updateById(cartInfo);
            }
            // 往订单流水表添加数据
            MlccBusinessWaterInfo wrater = new MlccBusinessWaterInfo();
            wrater.setOrderId(order.getId() + "").setType(3).setUserId(userDetail.getId() + "")
                    .setCostMoney(order.getOrderMoney().toString()).setYewuInstructions("正常订单，前端提交现货订单")
                    .setYewuDeatil("提交订单").setStatus(0).setRemark("现货下单提交订单，生成未支付现货订单")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                    .setSysOrgCode(userDetail.getOrgCode())
                    .setOrderSn(order.getOrderSn()).setStoreId(order.getStoreId()).setId(UUID.randomUUID().toString().substring(0, 15));
            businessWaterInfoMapper.insert(wrater);

            // 2、往订单跟踪表添加一条记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString().substring(0, 15)).setOrderSn(order.getOrderSn())
                    .setOrderType(3).setThing("创建订单").setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername()).setRemark("前端提交的订单");
            trackingOrderMapper.insert(trackingOrder);
            return order.getOrderSn();
        } else {
            return "0";
        }
    }

    /**
     * 购物车更新备注
     *
     * @param id     购物车id
     * @param remark 备注
     */
    @Override
    public int updateRemark(String id, String remark) {
        MlccThirdGoodsCart mlccCartInfo = cartMapper.selectById(id);
        mlccCartInfo.setRemark(remark);
        return cartMapper.updateById(mlccCartInfo);
    }

    /**
     * 改变购物车购买数量的方法
     *
     * @param id      大购物车id
     * @param smallid 小购物车id
     * @param num     购买数量
     */
    @Override
    public int updateByNum(String token, String id, String smallid, String num) {
        if (!fabricUtil.checkToken(token)) {
            new RuntimeException("token失效");
        }
        MlccThirdGoodsCart goodsCart = cartMapper.selectById(id);
        Double value = Double.valueOf(num);
        if (value > 0) {
            // 替换换来的购买数量
            MlccThirdCartBuynum buynum = cartBuynumMapper.selectById(smallid);
            if (buynum != null) {
                buynum.setBuyNum(value);
                cartBuynumMapper.updateById(buynum);
            }
        } else {
            // 删除这条记录
            cartBuynumMapper.deleteById(smallid);
        }
        // 重新统计购物车金额
        BigDecimal count = new BigDecimal(0);
        QueryWrapper<MlccThirdCartBuynum> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_cart_id", id).eq("status", 0);
        List<MlccThirdCartBuynum> list = cartBuynumMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            for (MlccThirdCartBuynum buynum : list) {
                count = count.add(new BigDecimal(buynum.getBuyNum()));
            }
            // 总数已经得到统计
            // 更新大购物车购买数量和价格
            return goodsOrderUtil.updateCartPrice(id, goodsCart.getGoodsId(), count.toString());
        }
        return 0;
    }
}
